package com.tpo.jnotes.client.layer.controller;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.SwingUtilities;

import com.tpo.jnotes.client.layer.binding.Binding;
import com.tpo.jnotes.client.layer.controller.commands.AboutCommand;
import com.tpo.jnotes.client.layer.controller.commands.AddCommand;
import com.tpo.jnotes.client.layer.controller.commands.DeleteCommand;
import com.tpo.jnotes.client.lib.action.ICommand;
import com.tpo.jnotes.client.lib.action.Invoker;
import com.tpo.jnotes.client.lib.interfaces.IController;
import com.tpo.jnotes.client.lib.interfaces.IModel;
import com.tpo.jnotes.client.lib.interfaces.IModelEntity;
import com.tpo.jnotes.client.lib.interfaces.IView;
import com.tpo.jnotes.client.lib.interfaces.IViewEntity;
import com.tpo.jnotes.client.main.Logging;

public class NotesController implements ActionListener, IController
{

    private IModel model;
    private IView view;
    private final Invoker commandInvoker;

    public NotesController( IView view, IModel model )
    {
        commandInvoker = new Invoker();
        setView( view );
        setModel( model );
    }

    private void setView( IView view )
    {
        this.view = view;
        this.view.setActionListener( this );
    }

    private void setModel( IModel model )
    {
        this.model = model;
        Binding.setModel( model );
        List< ? extends IModelEntity > notes = model.getEntities();
        if( notes.size() != 0 )
            for( int i = 0; i < notes.size(); i++ )
                view.add( notes.get( i ).getId() );
        else
            addDefaultNote();
    }

    private void addDefaultNote()
    {
        Logging.trace( "Controller > Default note added." );
        add();
    }

    @Override
    public void add()
    {
        IModelEntity newEntity = model.addEntity();
        view.add( newEntity.getId() );
    }

    @Override
    public void delete( int id )
    {
        model.deleteEntity( id );
        view.delete( id );
        if( view.count() == 0 )
            System.exit( 0 );
    }

    @Override
    public void actionPerformed( ActionEvent event )
    {
        ICommand command = null;
        if( event.getActionCommand().equalsIgnoreCase( AddCommand.ADD ) )
            command = new AddCommand( this );
        else if( event.getActionCommand().equalsIgnoreCase( DeleteCommand.DELETE ) )
        {
            IViewEntity viewComponent = (IViewEntity)SwingUtilities.getRoot( (Component)event.getSource() );
            command = new DeleteCommand( this, viewComponent.getId() );
        }
        else if( event.getActionCommand().equalsIgnoreCase( AboutCommand.ABOUT ) )
            command = new AboutCommand();
        commandInvoker.execute( command );
    }
}
